import katex from 'katex';

export function useKatexRender() {
  function renderMath(el: HTMLElement) {
    if (!el) return;

    function walk(node: Node) {
      if (node.nodeType === Node.TEXT_NODE) {
        const text = node.textContent || '';
        if (text.includes('$')) {
          // 拆分文本，找到 $...$ 公式部分
          const frag = document.createDocumentFragment();
          const parts = text.split(/(\$[^$]+\$)/g);

          parts.forEach(part => {
            if (part.startsWith('$') && part.endsWith('$')) {
              const math = part.slice(1, -1);
              const span = document.createElement('span');
              try {
                span.innerHTML = katex.renderToString(math, { throwOnError: false });
              } catch {
                span.textContent = part;
              }
              frag.appendChild(span);
            } else {
              frag.appendChild(document.createTextNode(part));
            }
          });

          node.parentNode?.replaceChild(frag, node);
        }
      } else if (node.nodeType === Node.ELEMENT_NODE) {
        // 递归处理子节点
        node.childNodes.forEach(child => walk(child));
      }
    }

    walk(el);
  }

  return { renderMath };
}
